import { getClassByTeacherIdUsingGet } from '@/services/student-management-system/banjimokuai';
import {
  addScoreUsingPost,
  updateScoreUsingPut,
} from '@/services/student-management-system/fenshumokuai';
import { listCourseByStudentIdAndTeacherIdAndClassIdUsingGet } from '@/services/student-management-system/kechengmokuai';
import { getUsersByClassIdUsingGet } from '@/services/student-management-system/yonghumokuai';
import { useModel } from '@@/exports';
import { Cascader, CascaderProps, Form, Input, message, Select } from 'antd';
import { forwardRef, useEffect, useImperativeHandle, useState } from 'react';

export interface UpdateScoreProps {
  editScore?: API.ScoreVO;
  onCloseModal?: () => void;
}

export interface UpdateScoreMethods {
  submitForm: () => Promise<boolean>;
  handleReset: () => void;
}

interface Option {
  value: number;
  label: string;
  children?: Option[];
}

const UpdateScore = forwardRef<UpdateScoreMethods, UpdateScoreProps>((props, ref) => {
  const { editScore, onCloseModal } = props;
  const [form] = Form.useForm();
  const [classAndStudentOptions, setClassAndStudentOptions] = useState<Option[]>([]);
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};
  const [selectClassStudent, setSelectClassStudent] = useState<boolean>(false);
  const [courseOptions, setCourseOptions] = useState<Option[]>([]);

  const submitForm = async (): Promise<boolean> => {
    // 获取表单提交数据 表单数据验证
    const values = await form.validateFields();
    console.log(values);
    const res = editScore?.id
      ? await updateScoreUsingPut({
          ...values,
          id: editScore.id,
          classId: values.classAndStudent[0],
          teacherId: currentUser?.id,
          status: editScore.status,
        })
      : await addScoreUsingPost({
          ...values,
          classId: values.classAndStudent[0],
          teacherId: currentUser?.id,
        });
    if (res.code === 200) {
      message.success('操作成功');
      onCloseModal?.();
      return true;
    } else {
      message.error('操作失败：' + res.msg);
      return false;
    }
  };

  const onChange: CascaderProps<Option>['onChange'] = async (value) => {
    if (value[1]) {
      form.setFieldsValue({ ...form, studentId: value[1] });
      setSelectClassStudent(true);
      form.setFieldsValue({ ...form, courseId: null });
      // 获取对应课程
      const [classId, studentId] = value;
      const teacherId = currentUser?.id ?? 0;
      const res = await listCourseByStudentIdAndTeacherIdAndClassIdUsingGet({
        classId,
        studentId,
        teacherId,
      });

      if (res.data) {
        const courseOpt = res.data.map((course) => ({
          value: course.id!,
          label: course.courseName ?? '',
        }));
        setCourseOptions(courseOpt);
      }
    }
  };

  // 清除表单数据
  const handleReset = () => {
    form.resetFields(); // 重置表单字段
  };

  useEffect(() => {
    // 权限判断
    if (currentUser?.role !== 1) {
      // 不能修改，无权限
      message.error('不为教师角色，不能操作！');
      onCloseModal?.();
      return;
    }
    // 初始化级联选择器options
    const fetchData = async () => {
      const res = await getClassByTeacherIdUsingGet({ teacherId: currentUser?.id ?? 0 });
      if (!res.data) return;

      const updatedOptions = await Promise.all(
        res.data.map(async (clazz) => {
          const classOption: Option = {
            value: clazz.id!,
            label: clazz.className ?? '',
            children: [],
          };

          // 获取学生数据
          const studentRes = await getUsersByClassIdUsingGet({ id: classOption.value });
          if (studentRes.data) {
            classOption.children = studentRes.data.map((student) => ({
              value: student.id ?? 0,
              label: student.realName ?? '',
            }));
          }
          return classOption;
        }),
      );

      setClassAndStudentOptions(updatedOptions);
    };

    if (editScore && editScore.classId && editScore.studentId) {
      // 如果有teacherId 判断是否为老师，且当前老师 不为当前老师 则不能操作
      if (editScore.teacherId && editScore.teacherId !== currentUser?.id) {
        // 不能修改，无权限
        message.error('不能修改非当前教师授课分数');
        onCloseModal?.();
        return;
      }
      form.setFieldsValue({
        classId: editScore.classId,
        courseId: editScore.courseId,
        studentId: editScore.studentId,
        status: editScore.status,
        id: editScore.id,
        score: editScore.score,
        classAndStudent: [editScore.classId, editScore.studentId], // 注意这里是数组！
        teacherId: editScore.teacherId,
        className: editScore.className,
        courseName: editScore.courseName,
        studentName: editScore.studentName,
        teacherName: editScore.teacherName,
      });
    }

    fetchData();
  }, [editScore]);

  useImperativeHandle(ref, () => ({
    submitForm,
    handleReset,
  }));

  return (
    <Form form={form} labelCol={{ span: 6 }} wrapperCol={{ span: 16 }} autoComplete="off">
      <Form.Item label="班级/学生" name="classAndStudent" rules={[{ required: true }]}>
        <Cascader
          options={classAndStudentOptions}
          onChange={onChange}
          placeholder="请选择班级和学生"
          fieldNames={{ value: 'value', label: 'label', children: 'children' }}
          showSearch
          changeOnSelect
        />
      </Form.Item>

      <Form.Item label="学生id" name="studentId" rules={[{ required: true }]}>
        <Input />
      </Form.Item>

      <Form.Item label="课程" name="courseId" rules={[{ required: true }]}>
        <Select
          disabled={!selectClassStudent}
          options={courseOptions}
          placeholder={'请先选择班级学生，再选择课程'}
        ></Select>
      </Form.Item>

      <Form.Item label="分数" name="score" rules={[{ required: true }]}>
        <Input type="number" step="0.5" />
      </Form.Item>
    </Form>
  );
});
export default UpdateScore;
